import Fly from "flyio/dist/npm/wx";
import { logger } from "@/utils/log";

let enableDebug = false;

const request = new Fly();

// fly.config.baseURL = process.env.BASE_API

// 请根据实际修改
request.config.baseURL = process.env.BASE_API;

// 临时内穿的服务（可能不稳定）
// request.config.baseURL = 'https://oreo-api.hagongyi.cn/'
request.config.timeout = 50000;

const noLoadingUrlList = ["/s-mall/api/event-tracking/upload"]

request.interceptors.request.use((request) => {
  const token = uni.getStorageSync("TOKEN");
  if (typeof token === "string" && token.trim() !== "") {
    // 只有 token 不为空, 才添加认证头
    request.headers["Authorization"] = `Bearer ${token}`;
  }
  if (enableDebug) {
    logger.info(
      request,
      `发起请求 模式：${request.method || "GET"} 地址：${request.url} 数据：${
        request.body
      }`
    );
    console.log("-----request detail start-----");
    console.log("request object:", request);
    console.log("body:", request.body);
    console.log("-----request detail end-----");
  }
	if (!noLoadingUrlList.includes(request.url) && !request.url.includes('s-mall/api/panda-video/detail')) {
		uni.showLoading({ title: "请求中" });
	}
  return request;
});

const urlList = ["/s-mall/api/member/info-with-score"];

const noToastUrlList = ["/s-coupon/api/redeem/redeem", "/s-mall/api/member/cancel-member", "/s-mall/api/event-tracking/upload"];

request.interceptors.response.use(
  (response) => {
    uni.hideLoading();

    const data = response?.data;
    const responseCode = data?.code ?? null;

    if (enableDebug) {
      logger.info(
        response,
        `请求响应 模式：${response.request.method || "GET"} 地址：${
          response.request.url
        } 数据：${response.data}`
      );
    }
    // 全局用户信息储存
    if (urlList.includes(response.request.url)) {
      console.log("全局~~~~~~", urlList.includes(response.request.url));
      getApp().globalData.user = data.data || {};
    }
    // 协定业务错误code处理
    if (
      [422].includes(responseCode) &&
      !noToastUrlList.includes(response.request.url)
    ) {
      setTimeout(() => {
        uni.showToast({
          title: data.message,
          icon: "none",
        });
      });

      throw Error(data.message);
    }
    if (![200].includes(responseCode)) {
      throw Error(data.message);
    }
    if ([401].includes(responseCode)) {
      uni.clearStorageSync();
      getApp().globalData.user = {};
      setTimeout(() => {
        uni.showToast({
          title: "登录已过期，请重新登录~",
          icon: "none",
        });
      });

      throw Error("need login");
    }
    return data;
  },
  (err) => {
		logger.error(`error：`, err);
    uni.hideLoading();
    if (err.status === 500) {
      setTimeout(() => {
        uni.showToast({
          title: "服务器错误，请稍后重试",
          icon: "none",
        });
      });
    }
    if (err.engine?.response?.code === 401 && !noToastUrlList.includes(err.engine._options.url)) {
      uni.clearStorageSync();
      getApp().globalData.user = {};
      setTimeout(() => {
        uni.showToast({
          title: "登录已过期，请重新登录~",
          icon: "none",
        });
      });
    }
    // throw Error(err.response?.data?.message)
    return Promise.resolve(err.engine?.response);
  }
);

export default request;
